<?php
/*
 * Author :pandiam
 */
session_start();

if (!isset($_SESSION['uid']) || $_SESSION['uid'] == -1) {
    header('Location: login.php');
}

require_once ('../FrameWorks/Objects/attribute.php');
require_once ('../FrameWorks/Objects/category.php');
require_once ('include/functions.php');
require_once ('../BL/BL.php');

$attributes = array();
$error_attr = "";

function createAttributeList()
{
    global $attributes, $error_attr;
    $attrib = split(",", $_POST['data']);
    $i = 0;
    $error = "";
    foreach ($attrib as $attribute) {
        $values = split("~", $attribute);
        $attr = new Attribute();
        $attr->setName($values[0]);
        
        if(strcmp($values[1],"measurable") ==0)
            $attr->setType("m");
        else if(strcmp($values[1],"unmeasurable") ==0)
            $attr->setType("u");
        else
            $attr->setType("n");
        
        $attr->SetBestValue($values[2]);

        $error = $values[0] . "~" . $values[1] . "~" . $values[2];

        if (strcmp($values[2], "close_to") == 0) {
            $attr->SetCloseToValue($values[3]);
            $error = $error . "~" . $values[3];
        }
        $attributes[$i] = $attr;
        if ($error_attr == "")
            $error_attr = $error;
        else
            $error_attr = $error_attr . "-" . $error;
        $i++;
        $error = "";
    }
}

createAttributeList();
$cat = new Category();
$cat->SetName($_POST['catname']);
$cat->SetOwner($_SESSION['uid']);
$cat->SetPrivacy($_POST['catType']);
$cat->SetAttributes($attributes);

if (BL_createCategory($cat, $_SESSION['uid']) < 0) {
    UI_registerError('msg_error', "Category already exists");
    UI_registerError('msg_warning', "Please choose a different category name");
    $_SESSION['error'] = $error_attr;
    header("location: profile.php");
} else {
    UI_registerError('msg_success', "Category created successfully");
    UI_registerError('msg_info', "Category inserted in your \"My categories\" page");
    header("location: profile.php");
}
?>